package com.jhg.drgclinicalpathway.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jhg.drgclinicalpathway.dao.JC参数设置Dao;
import com.jhg.drgclinicalpathway.dao.PatientDao;
import com.jhg.drgclinicalpathway.dao.sys.AccountDao;
import com.jhg.drgclinicalpathway.dao.sys.SysOpsDao;
import com.jhg.drgclinicalpathway.dao.sys.SysPermDao;
import com.jhg.drgclinicalpathway.dao.sys.SysRoleDao;
import com.jhg.drgclinicalpathway.domain.Dis2Pathway;
import com.jhg.drgclinicalpathway.domain.JC参数设置;
import com.jhg.drgclinicalpathway.domain.RpnMsg;
import com.jhg.drgclinicalpathway.domain.SysOps;
import com.jhg.drgclinicalpathway.domain.sys.AccountInfo;
import com.jhg.drgclinicalpathway.domain.sys.SysPerm;
import com.jhg.drgclinicalpathway.domain.sys.SysRole;
import com.jhg.drgclinicalpathway.utils.JWTUtils;
import com.jhg.drgclinicalpathway.utils.PassToken;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("sys")
public class SysController {


    @Autowired
    SysRoleDao roleDao;

    @GetMapping("roles")
    public RpnMsg roles() {
        List<SysRole> sysRoles = roleDao.selectList(null);
        return RpnMsg.SUCCESS(sysRoles);
    }

    @Autowired
    SysOpsDao sysOpsDao;

    @ApiOperation("系统操作日志")
    @PostMapping("sysops")
    public RpnMsg sysops(@RequestBody SysOps op) {
        try {
            op.setId(UUID.randomUUID().toString());
            op.setCtime(new Date());
            sysOpsDao.insert(op);
        } catch (Exception ex) {
        }
        return RpnMsg.SUCCESS();
    }

    /**
     * 更新最后一次登录时间
     *
     * @param user
     * @return
     */
    @PostMapping("sys-login-last")
    public RpnMsg sysLoginLast(@RequestParam("user") String user) {
        try {
            if (StringUtils.isEmpty(user)) return RpnMsg.SUCCESS();
            AccountInfo byUserName = accountDao.findByUserName(user);
            if (byUserName == null) return RpnMsg.SUCCESS();
            byUserName.set登陆时间(new Date());
            accountDao.updateById(byUserName);
        } catch (Exception e) {
        }
        return RpnMsg.SUCCESS();
    }

    @GetMapping("sysops-list")
    public RpnMsg sysopsList(
            @RequestParam("stime") String stime,
            @RequestParam("etime") String etime,
            @RequestParam(defaultValue = "") String s,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {

        Page<SysOps> pageInfo = new Page<SysOps>(page, size);
        QueryWrapper<SysOps> queryWrapper = new QueryWrapper<SysOps>();

        queryWrapper.between("ctime", stime + " 00:00:00", etime + " 23:59:59");

        if (!StringUtils.isEmpty(s)) {
            s = s.trim();
            queryWrapper.like("name", "%" + s + "%")
                    .or().like("title", "%" + s + "%")
                    .or().like("depts", "%" + s + "%");
        }
        queryWrapper.orderByDesc("ctime");
        IPage<SysOps> accountPage = sysOpsDao.selectPage(pageInfo, queryWrapper);
        return RpnMsg.SUCCESS(accountPage);
    }

    @Autowired
    SysPermDao permDao;

    @ApiOperation("增加、修改角色")
    @PostMapping("role")
    public RpnMsg role(@RequestBody SysRole role) {

        boolean isNew = StringUtils.isEmpty(role.getId());
        if (isNew) {
            role.setId(UUID.randomUUID().toString());
            roleDao.insert(role);
        } else {
            roleDao.updateById(role);
        }

        QueryWrapper<SysPerm> queryWrapper = new QueryWrapper<SysPerm>();
        queryWrapper.eq("rid", role.getId());
        permDao.delete(queryWrapper);

        if (role.getPerms() != null && role.getPerms().size() > 0) {
            for (String perm : role.getPerms()) {
                permDao.insert(new SysPerm(UUID.randomUUID().toString(), role.getId(), perm));
            }
        }

        return RpnMsg.SUCCESS();
    }

    @GetMapping("role-id")
    public RpnMsg roleId(String id) {
        SysRole sysRole = roleDao.selectById(id);
        QueryWrapper<SysPerm> queryWrapper = new QueryWrapper<SysPerm>();
        queryWrapper.eq("rid", id);
        List<SysPerm> sysPerms = permDao.selectList(queryWrapper);
        if (sysPerms != null && sysPerms.size() > 0) {
            List<String> mIds = sysPerms.stream().map(it -> it.getMid()).collect(Collectors.toList());
            sysRole.setPerms(mIds);
        }
        return RpnMsg.SUCCESS(sysRole);
    }

    @GetMapping("destory-id")
    public RpnMsg destoryById(String id) {

        roleDao.deleteById(id);
        QueryWrapper<SysPerm> queryWrapper = new QueryWrapper<SysPerm>();
        queryWrapper.eq("rid", id);
        permDao.delete(queryWrapper);

        return RpnMsg.SUCCESS();
    }

    @Autowired
    AccountDao accountDao;

    /**
     * 登录账号列表
     *
     * @param s
     * @return
     */
    @GetMapping("users")
    public RpnMsg users(@RequestParam(defaultValue = "") String s,
                        @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer size,
                        @RequestParam String stime,
                        @RequestParam String etime,
                        @RequestParam(defaultValue = "false") String nonelogin
    ) {

        Page<AccountInfo> pageInfo = new Page<AccountInfo>(page, size);
        QueryWrapper<AccountInfo> queryWrapper = new QueryWrapper<AccountInfo>();
        if (!StringUtils.isEmpty(s)) {
            s = s.trim();
            queryWrapper.like("姓名", "%" + s + "%").or().like("用户名", "%" + s + "%");
        }

        if (Boolean.parseBoolean(nonelogin)) {
            queryWrapper.notBetween("ISNULL(登陆时间,'1971-01-01 00:00:00')", stime + " 00:00:00", etime + " 23:59:59");
        } else {
            queryWrapper.between("登陆时间", stime + " 00:00:00", etime + " 23:59:59");
        }

        IPage<AccountInfo> accountPage = accountDao.selectPage(pageInfo, queryWrapper);
        return RpnMsg.SUCCESS(accountPage);
    }

    @PassToken
    @PostMapping("login")
    public RpnMsg login(@RequestBody Map<String, Object> map) {

        String username = map.getOrDefault("username", "").toString();
        String password = map.getOrDefault("password", "").toString();
        username = username.trim();
        password = password.trim();

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return RpnMsg.FAIL("用户名或密码不能为空！");
        }
        AccountInfo user = accountDao.findByUserName(username);

        if (user == null) {
            return RpnMsg.FAIL("不存在相关帐号！");
        }
        if (!user.get密码().equals(password)) {
            return RpnMsg.FAIL("密码错误！");
        }
        user.set登陆时间(new Date());
        accountDao.updateById(user);
        String token = JWTUtils.getToken(user);
        JSONObject o = new JSONObject();
        o.put("accessToken", token);
        return RpnMsg.SUCCESS(o);
    }

    @Autowired
    PatientDao patientDao;

    @PostMapping("userinfo")
    public RpnMsg userinfo(HttpServletRequest req) {

        String token = req.getHeader("X-Access-Token");
        String uname = JWTUtils.getClaimByName(token, "username").asString();
        AccountInfo user = accountDao.findByUserName(uname);
        JSONObject o = new JSONObject();
        o.put("name", user.get姓名());
        o.put("user", user.get用户名());
        o.put("userId", user.getId());
        o.put("rolesId", user.get管理员());
        o.put("roles", new String[]{"admin"});
        List<Map<String, Object>> 科室医生s = patientDao.科室医生();
        //获取医生所属科室
        List<String> depts = 科室医生s.stream()
                .filter(m -> m.getOrDefault("医生", "").toString().equals(user.get姓名()))
                .map(m -> m.getOrDefault("科室", "").toString())
                .filter(it -> !StringUtils.isEmpty(it))
                .collect(Collectors.toList());
        o.put("depts", depts);
        return RpnMsg.SUCCESS(o);
    }

    @PostMapping("ed-setting")
    public RpnMsg edSetting(@RequestBody JC参数设置 m) {

        //Integer t=new Date().getTime();
        long t = new Date().getTime();
        int id = (int) t;
        boolean n = false;
        if (m.getId() == null) {
            m.setId(id);
            n = true;
        }
        if (n) {
            jc参数设置Dao.insert(m);
        } else {
            jc参数设置Dao.updateById(m);
        }

        return RpnMsg.SUCCESS();

    }

    @Autowired
    JC参数设置Dao jc参数设置Dao;

    @GetMapping("jc-settings")
    public RpnMsg jcSettings(@RequestParam(defaultValue = "") String s) {

        QueryWrapper<JC参数设置> queryWrapper = new QueryWrapper<JC参数设置>();

        if (!StringUtils.isEmpty(s)) {
            queryWrapper.like("名称", s);
        }
        List<JC参数设置> ls = jc参数设置Dao.selectList(queryWrapper);
        return RpnMsg.SUCCESS(ls);

    }


}
